import React, { useEffect, useState } from "react";
import { Layout, Menu } from "@arco-design/web-react";
import { IconCaretRight, IconCaretLeft } from "@arco-design/web-react/icon";
import { useLocation, useNavigate } from "react-router-dom";
import { routes } from "./routes";
import "./layout.css";
import { Outlet } from "react-router-dom";

const MenuItem = Menu.Item;
const SubMenu = Menu.SubMenu;
const Sider = Layout.Sider;
const Content = Layout.Content;

function MyLayout(props) {
  const [collapsed, setCollapsed] = useState(false);
  const [selectKey, setSelectKey] = useState(routes[0].path);
  const [openKeys] = useState([]); // setOpenKeys

  const location = useLocation();
  const navigate = useNavigate();

  const handleCollapsed = () => {
    setCollapsed(!collapsed);
  };

  const onClickMenuItem = (key) => {
    if (key === location.pathname) {
      return;
    }
    
    navigate(key);
    setSelectKey(key);
  };

  useEffect(() => {
    setSelectKey(location.pathname);
  }, [location.pathname]);

  return (
    <Layout className="layout">
      <Sider
        collapsed={collapsed}
        onCollapse={handleCollapsed}
        collapsible
        trigger={collapsed ? <IconCaretRight /> : <IconCaretLeft />}
        breakpoint="xl"
      >
        <Menu
          defaultOpenKeys={openKeys}
          selectedKeys={[selectKey]}
          onClickMenuItem={onClickMenuItem}
          style={{ width: "100%" }}
        >
          {routes.map((item) => {
            if (item?.children && item.children?.length) {
              return (
                <SubMenu key={item.path} title={item.name}>
                  {item.children.map((childItem) => (
                    <MenuItem key={childItem.path}>
                      {childItem.icon}
                      {childItem.name}
                    </MenuItem>
                  ))}
                </SubMenu>
              );
            }
            return (
              <MenuItem key={item.path}>
                {item.icon}
                {item.name}
              </MenuItem>
            );
          })}
        </Menu>
      </Sider>
      <Layout>
        <Layout style={{ padding: "0 24px" }}>
          <Content>
            <Outlet />
          </Content>
        </Layout>
      </Layout>
    </Layout>
  );
}

export default MyLayout;
